package collect.taobao.util.page;

import java.sql.*;
import java.util.*;

abstract public class PageBuild{
  public abstract Object getObject(ResultSet rs);

  public PageBuffer buildPage(ResultSet rs, int startPage, int rowsPerPage,
                        String url) {
    int recordCounter = 0; //max record counter
    int maxPage = 0; //total pages
    PageBuffer page = null;
    ArrayList items = new ArrayList();
    int start, end;
    if (startPage < 1) {
      startPage = 1;
      //start page index based 1
    }
    start = (startPage - 1) * rowsPerPage + 1;
    end = (startPage) * rowsPerPage;
    try {
      while (rs.next()) { //record exist
        recordCounter = recordCounter + 1;
        if ( (recordCounter >= start) && (recordCounter <= end)) { //find recoed wanted
          items.add(getObject(rs)); //
        }
      }
    }
    catch (SQLException e) {
      e.printStackTrace();
    }
    if (recordCounter == 0) {
      return PageBuffer.EMPTY_PAGE;
    }
    maxPage = getMaxPage(recordCounter, rowsPerPage);
    if (startPage > maxPage) {
      startPage = maxPage;
    }
    page = new PageBuffer(items, startPage, maxPage, url,recordCounter);
    return page;
  }
  public PageBuffer buildPage(ResultSet rs, int startPage, int rowsPerPage,int recordCounter,
                   String url) {
       //max record counter
      int maxPage = 0; //total pages
      PageBuffer page = null;
      ArrayList items = new ArrayList();
      if (startPage < 1) {
         startPage = 1;
       //start page index based 1
      }
      int count=0;
      try {
       while (rs.next()) { //record exist
count++;
           items.add(getObject(rs)); //
//System.out.println(count);
       }
      }
      catch (SQLException e) {
       e.printStackTrace();
      }
      if (recordCounter == 0) {
       return PageBuffer.EMPTY_PAGE;
      }
      maxPage = getMaxPage(recordCounter, rowsPerPage);
      if (startPage > maxPage) {
       startPage = maxPage;
      }

      page = new PageBuffer(items, startPage, maxPage, url,recordCounter);

      return page;
      }

  private int getMaxPage(int recordCount, int rowsPerPage) {
    int maxPage;
    if (recordCount % rowsPerPage == 0) {
      maxPage = recordCount / rowsPerPage;
    }
    else {
      maxPage = recordCount / rowsPerPage + 1;
    }
    return maxPage;
  }
}
